package com.itheima.springbootwebtlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.ClazzMapper;
import com.itheima.springbootwebtlias.mapper.StudentMapper;
import com.itheima.springbootwebtlias.pojo.Clazz;
import com.itheima.springbootwebtlias.pojo.ClazzQueryParam;
import com.itheima.springbootwebtlias.pojo.Emp;
import com.itheima.springbootwebtlias.pojo.PageResult;
import com.itheima.springbootwebtlias.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    //添加班级
    @Override
    public void addClazzs(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazzs(clazz);
    }

    //查询所有班级
    @Override
    public List<Clazz> selectAll() {
        return clazzMapper.selectAll();
    }

    //班级列表查询 分页查询
    @Override
    public PageResult page(ClazzQueryParam queryParam) {
        //1.使用分页插件来实现分页查询
        //1.1 启动分页插件                   页码                  条数
        PageHelper.startPage(queryParam.getPage(),queryParam.getPageSize());

        //1.2 调用被分页插件增强的持久层方法
        Page<Clazz> page = clazzMapper.selectByCondition(queryParam);

        //1.3 从分页插件增强方法的返回结果中，获取数据封装到PageResult返回
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    //删除班级
    @Override
    public void deleteById(Integer id) {
        Integer count = studentMapper.selectByClazzId(id);
        if (count != 0){
            throw new DeletionIsNotAllowed("当前班级下存在学生，不允许删除");
        }
        clazzMapper.deleteById(id);
    }

    //根据id查询
    @Override
    public Clazz findById(Integer id) {
        Clazz clazz = clazzMapper.findById(id);
        return clazz;
    }

    //修改班级
    @Override
    public void update(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.update(clazz);
    }
}
